package com.ny.controller;

import com.ny.entity.Device;
import com.ny.entity.Result;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    // 查询所有设备接口
    @GetMapping("/findAll")
    public Result findAll() {
        List<Device> devices = deviceService.findAllDevices();
        return Result.success(devices);
    }

    // 添加设备接口
    @PostMapping("/add")
    public Result addDevice(@RequestBody Device device) {
        Device savedDevice = deviceService.saveDevice(device);
        return Result.success("设备添加成功", savedDevice);
    }

    // 根据device_id删除设备接口
    @DeleteMapping("/delete/{deviceId}")
    public Result deleteDevice(@PathVariable Integer deviceId) {
        boolean isDeleted = deviceService.deleteDeviceByDeviceId(deviceId);
        if (isDeleted) {
            // 顺序：message（String）、data（null，删除成功无数据）
            return Result.success("设备删除成功", null);
        } else {
            return Result.error("设备不存在或删除失败");
        }
    }

    // 修改设备状态接口
    @PutMapping("/updateStatus")
    public Result updateDeviceStatus(@RequestParam Integer deviceId, @RequestParam Integer status) {
        Optional<Device> updatedDevice = deviceService.updateDeviceStatus(deviceId, status);

        if (updatedDevice.isPresent()) {
            // 顺序：message（String）、data（Device）
            return Result.success("设备状态更新成功", updatedDevice.get());
        } else {
            return Result.error("设备不存在或更新失败");
        }
    }
}